package com.page.action.base;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.SessionAware;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;

import com.opensymphony.xwork2.ActionSupport;


/**
 * @Package com.net263.ccap.action.base
 * @File BaseAction.java
 * @author shuxin.zheng@net263.com 
 * @date 2014-9-28 下午01:20:48
 */
public class BaseAction extends ActionSupport implements SessionAware {

    private static final long serialVersionUID = 1L;
    //private static final Logger log = LoggerFactory
    //    .getLogger(BaseAction.class);

    private Map<String, Object> session;
    
    /**
     * 发送  JSON 对象至浏览器
     * @param jsonObject
     * @return {boolean} 是否成功
     */
    protected boolean reply(JSONObject jsonObject) {
        return reply(jsonObject, "text/json;charset=utf-8");
    }
  
    /**
     * 发送   JSON 字符串至浏览
     * @param data HTTP 响应数据
     * @param contentType HTTP 响应头中的内容类
     * @return {boolean} 是否成功
     */
    protected boolean reply(JSONObject data, String contentType) {
        HttpServletResponse response = ServletActionContext.getResponse();
        response.setContentType(contentType);
        response.setCharacterEncoding("UTF-8");
        response.setHeader("cache-control", "no-cache");
        
        PrintWriter out = null;
        try {
            out = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
            if (out != null)
                out.close();
            return false;
        }  
        out.print(data);  
        out.flush();
        out.close();
        return true;
    }
    
    public void setSession(Map<String, Object> session) {
        this.session = session;
    }

    /**
     * 获得session
     *  @author wangtao
     *  @date 2014-10-13
     *  @return session
     */
    public Map<String, Object> getSession() {
        return session;
    }
    
    /**
     * 从Session获得用户
     *  @author wangtao
     *  @date 2014-10-13
     *  @return {map} Session中所有用
     */
    @SuppressWarnings("unchecked")
    public Map<String, Object> getSessionUsers() {
        return (Map<String, Object>) session.get("usersMap");
    }
    
}
